﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PacoToolKit.Json
{
    /// <summary>
    /// 序列化器
    /// </summary>
    public static class Serializer
    {
        /// <summary>
        /// 序列化对象成json字符串
        /// </summary>
        /// <param name="o">多种对象object||collection||dictionary</param>
        /// <returns></returns>
        public static string SerializeObject(object o)
        {
            return JsonConvert.SerializeObject(o, Formatting.None);
        }
        /// <summary>
        /// 序列化对象成格式化的json字符串（方便阅读）
        /// </summary>
        /// <param name="o">多种对象object||collection||dictionary||DataSet</param>
        /// <returns></returns>
        public static string SerializeObjectFormat(System.Object o)
        {
            return JsonConvert.SerializeObject(o, Formatting.Indented);
        }

        /// <summary>
        /// 序列化对象添加到文件（文件不存在则创建）
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="o"></param>
        public static void SerializeObjectInFile(string fileName, object o)
        {
            System.IO.File.AppendAllText(fileName, JsonConvert.SerializeObject(o));
        }

        /// <summary>
        /// 序列化对象到新文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="o"></param>
        public static void SerializeObjectToFile(string fileName, object o)
        {
            //直接方式写入
            //System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(o));
            //间接方式写入
            using (System.IO.StreamWriter file = System.IO.File.CreateText(fileName))
            {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(file, o);
            }
        }
    }

}
